//
//  TabBar.m
//  OrderSys
//
//  Created by JM on 15-9-22.
//  Copyright (c) 2015年 zjlskj. All rights reserved.
//

#import "TabBar.h"
#import "TabBarButton.h"

@interface TabBar()
    
@property (nonatomic, weak) UIButton *selectedButton;

@end
@implementation TabBar

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
       //添加按钮
        //[self addBtns];
    }
    return self;
}

//提供一个方法给外界创建按钮
- (void)addTabBarButtonWithName:(NSString *)name selName:(NSString *)sel{
    UIButton *btn = [TabBarButton buttonWithType:UIButtonTypeCustom];
    //设置按钮的图片
   // imageName = [NSString stringWithFormat:@"TabBar%d",i];
    [btn setImage:[UIImage imageNamed:name] forState:UIControlStateNormal];
     [btn setImage:[UIImage imageNamed:sel] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    [self addSubview:btn];

}

- (void)btnClick:(UIButton *)button {
    _selectedButton.selected = NO;
    button.selected = YES;
    _selectedButton = button;
    //切换控制器
    if ([_delegate respondsToSelector:@selector(tabBar:didSelectedIndex:)]){
        [_delegate tabBar:self didSelectedIndex:button.tag];
    }
}

//设置按钮位置
- (void)layoutSubviews{
    [super layoutSubviews];
    CGFloat btnW = self.bounds.size.width / self.subviews.count;
    CGFloat btnH = self.bounds.size.height;
    CGFloat btnX = 0;
    CGFloat btnY = 0;
    //设置按钮的尺寸
    for (int i = 0 ;i < self.subviews.count; i++){
        UIButton *btn = self.subviews[i];
        btn.tag = i;
        btnX = i * btnW;
        btn.frame = CGRectMake(btnX, btnY, btnW, btnH);
        if(i == 0){
            [self btnClick:btn];
        }
    }
}
@end
